<?php

namespace RjYst\ExcelExport\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class UninstallExcelExportCommand extends Command
{
    protected $signature = 'rj:uninstall-excel-export {--keep-files : 保留已发布的文件}';
    protected $description = 'Uninstall RjYst Excel Export Package';

    public function handle()
    {
        $this->info('🗑️ 开始卸载 RjYst Excel Export Package...');

        if (!$this->confirm('确定要卸载 Excel 导出功能吗？')) {
            $this->info('❌ 卸载已取消');
            return;
        }

        // 1. 移除生成的文件
        if (!$this->option('keep-files')) {
            $this->removeGeneratedFiles();
        }

        // 2. 移除路由
        $this->removeRoutes();

        // 3. 移除配置文件
        if (!$this->option('keep-files')) {
            $this->removeConfig();
        }

        $this->info('✅ RjYst Excel Export Package 卸载完成！');
        $this->warn('注意：请手动移除 maatwebsite/excel 包（如果不需要）: composer remove maatwebsite/excel');
    }

    protected function removeGeneratedFiles()
    {
        $this->info('📦 移除生成的文件...');

        $files = [
            app_path('Admin/Exports/Sheet/CategorySheet.php'),
            app_path('Admin/Exports/CategoryExport.php'),
            app_path('Admin/Controllers/Export/ExcelExportController.php'),
            app_path('Admin/Actions/Category/DataExport.php'),
        ];

        foreach ($files as $file) {
            if (File::exists($file)) {
                File::delete($file);
                $this->line("   - 删除: {$file}");
            }
        }

        // 删除空目录
        $directories = [
            app_path('Admin/Exports/Sheet'),
            app_path('Admin/Controllers/Export'),
            app_path('Admin/Actions/Category'),
        ];

        foreach ($directories as $dir) {
            if (File::exists($dir) && File::isDirectory($dir) && count(File::files($dir)) === 0) {
                File::deleteDirectory($dir);
                $this->line("   - 删除空目录: {$dir}");
            }
        }

        $this->info('✅ 文件清理完成');
    }

    protected function removeRoutes()
    {
        $this->info('🔗 移除路由配置...');

        $routesFile = app_path('Admin/routes.php');

        if (!File::exists($routesFile)) {
            $this->info('ℹ️ Admin 路由文件不存在，跳过路由清理');
            return;
        }

        $routes = File::get($routesFile);

        // 移除导出路由
        $routes = preg_replace("/\s*\\\$router->get\('\/dataExport',\s*'Export\\\\ExcelExportController@dataExport'\);\s*/", '', $routes);

        File::put($routesFile, $routes);
        $this->info('✅ 路由配置清理完成');
    }

    protected function removeConfig()
    {
        $this->info('⚙️ 移除配置文件...');

        $configFile = config_path('rj-excel-export.php');

        if (File::exists($configFile)) {
            File::delete($configFile);
            $this->line("   - 删除: {$configFile}");
        }

        $this->info('✅ 配置文件清理完成');
    }
}
